<template>
  <van-tabs v-model="active">
    <van-tab title="投标信息">
      <mu-container class="container">
        <mu-form ref="form" :model="validateForm" class="mu-form">
          <mu-form-item label="投标人名称" prop="bidder" :rules="usernameRules">
            <mu-text-field v-model="validateForm.bidder" prop="bidder" @change="isorderindate"></mu-text-field>
          </mu-form-item>
          <mu-form-item label="法人名称" prop="frname" :rules="passFrRules">
            <mu-text-field type="frname" v-model="validateForm.frname" prop="frname"></mu-text-field>
          </mu-form-item>
          <mu-form-item label="法人身份证" prop="frid" :rules="passwordRules">
            <mu-text-field type="frid" v-model="validateForm.frid" prop="frid"></mu-text-field>
          </mu-form-item>
        </mu-form>
      </mu-container>
    </van-tab>
    <van-tab title="招标信息">
      <mu-container class="container">
        <mu-form ref="form" :model="validateForm" class="mu-form">
          <mu-form-item>
            <div>单位名称：{{validateForm.bidder}}</div>
          </mu-form-item>
          <mu-button flat color="primary" class="form_btn" @click="goPrve">修改</mu-button>

          <mu-form-item label="推荐码">
            <mu-text-field placeholder="请输入邀请人编码（非必填）" v-model="validateForm.invitecode">
            </mu-text-field>
          </mu-form-item>
          <mu-form-item label="开标时间" prop="kbtime" :rules="kbtimeRules">
            <mu-date-input placeholder="必填" v-model="validateForm.kbtime" container="bottomSheet" no-display label-float
              full-width @change="setTIme">
            </mu-date-input>
          </mu-form-item>
          <mu-form-item label="保函类型" prop="guaranteetype" :rules="typenameRules">
            <mu-select v-model="validateForm.guaranteetype" full-width @change="selectType">
              <mu-option label="银行保函" value="银行保函"></mu-option>
              <!-- <mu-option label="公司保函" value="公司保函"></mu-option> -->
            </mu-select>
          </mu-form-item>
          <div class="form_flex">
            <mu-form-item label="投标有效期" prop="indatenum" :rules="passwordRules" style="width:34%;">
              <mu-select v-model="validateForm.indatenum" tags @change="setTIme" type="number">
                <mu-option v-for="(day,index) in days" :key="index" :label="day" :value="day">
                  <!-- <mu-option v-for="language,index in languages" :key="language" :label="language" :value="language"></mu-option> -->
                </mu-option>
              </mu-select>
            </mu-form-item>
            <div class="form_indate">保函有效期：{{validateForm.enddate}}</div>
          </div>
          <div class="form_flex">
            <mu-form-item label="保证金金额" prop="earnest" :rules="passwordRules">
              <mu-text-field disabled v-model="validateForm.earnest" prop="earnest" @blur="changeEar"></mu-text-field>
            </mu-form-item>
            <div class="form_unit">万元</div>
            <mu-form-item label="办理费用" prop="earnest">
              <span style="font-size:16px;height:40px;line-height:45px;text-align:right;"><span style="color:#009688"
                  ref="price">{{validateForm.amount}}</span> 元 </span>
            </mu-form-item>
          </div>

          <mu-form-item label="项目及标段名称" prop="bidsection">
            <mu-text-field placeholder="请按招标文件填写，示例：AAAAAA项目（AAAA标段）" v-model="validateForm.bidsection"
              prop="bidsection">
            </mu-text-field>
          </mu-form-item>
        </mu-form>
      </mu-container>
    </van-tab>
    <van-tab title="资料上传">
      <mu-container class="form_container">
        <mu-paper class="demo-paper" :z-depth="1">
          <div style="font-size:16px;">河北*****有限公司 <mu-button style="color:#3f51b5" flat @click="viewAddress">查看寄回地址
            </mu-button>
          </div>
          <div>出函行：中国建设银行</div>
          <div>今日16点前支付订单，预计最晚48小时内出函</div>
          <van-rate v-model="vendorObj.stars" disabled disabled-color="rgb(255, 210, 30)" />
        </mu-paper>

        <mu-paper class="demo-paper" :z-depth="1" v-for="(item,index) in filelist" :key="index"
          :style="{marginBottom:(index === filelist[filelist.length-1] ? '60px':'15px')}">
          <div style="font-size:16px;">{{item.filename}}
          </div>
          <div>请用模板按示例制作。<van-button v-if="item.filename !== '招标文件'" size="mini" type="info"
              @click="view(item.demofileurl)">示例</van-button>
          </div>
          <div style="margin-bottom:10px;">文件格式：{{item.filetypes}}</div>
          <div style="margin-bottom:10px;color:#00897b;" v-if="item.isupload == '1'">已上传文件：{{item.filename}}</div>
          <div style="position:relative;">
            <mu-button small class="mu-buttons" data-mu-loading-size="22" color="primary" style="width:49%">本地上传
            </mu-button>
            <input id="uploaderInput" class="uploader__linput" type="file" accept="" capture="" style=""
              @change="fileInput_change($event,item)">
            <mu-button small class="mu-buttons" data-mu-loading-size="22" color="primary" style="width:49%">拍照上传
            </mu-button>
            <input id="uploaderInput" class="uploader__rinput" type="file" accept="image/*" capture="camera" style=""
              @change="fileInput_change($event,item)">
          </div>
        </mu-paper>

        <mu-paper class="demo-paper form_submit" :z-depth="1">
          <mu-button class="form_creat" @click="creatOrder">创建订单</mu-button>
        </mu-paper>
      </mu-container>
    </van-tab>
  </van-tabs>
</template>

<script>
  import Loading from 'muse-ui-loading';
  import 'muse-ui-loading/dist/muse-ui-loading.css';
  import {
    ImagePreview
  } from 'vant';
  export default {
    data() {
      return {
        usernameRules: [{
          validate: (val) => !!val,
          message: '必须填写投标人名称'
        }, ],
        passwordRules: [{
            validate: (val) => !!val,
            message: '必须填写法人身份证'
          },
          {
            validate: (val) => /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(val),
            message: '身份证号格式错误'
          }
        ],
        passFrRules: [{
          validate: (val) => !!val,
          message: '必须填写法人名称'
        }],
        kbtimeRules: [{
          validate: (val) => !!val,
          message: '必须填写开标时间'
        }],
        passwordRules: [{
          validate: (val) => !!val,
          message: '必须填投标有效期'
        }, ],
        typenameRules: [{
          validate: (val) => !!val,
          message: '必须选择保函类型'
        }, ],
        validateForm: {
          earnest: '',
          amount: '',
          kbtime: '',
          bidsection: '',
          username: '',
          password: '',
          isAgree: false,
          guaranteetype: '',
          bidder: ''
        },
        days: ['30', '60', '120'],
        firstForm: {},
        vendorList: [],
        vendorObj: {},
        filelist: {},
        active: 0
      }
    },
    methods: {
      isorderindate(e) {
        let _this = this;
        _this.$api.isorderindate({
          biddner: e
        }).then(function (data) {
          if (data.isindate === 'true') {
            _this.$dialog.alert({
              message: '在投标有效期内，不同投标人不能重复申请'
            })
            _this.validateForm.bidder = ''
          } else {
            
          }
        })
      },
      selectType(e) {
        this.validateForm.guaranteetype = e;
        this.changeEar();
        this.getselvendorlist();
      },
      getselvendorlist() {
        console.log(this.validateForm)
        let _this = this;
        const query = {
          pageindex: 1,
          pagesize: 1,
          isquick: '0',
          earnest: '0',
          sortname: 'addtime',
          sortorder: 'desc',
          guaranteetype: _this.validateForm.guaranteetype
        }
        let rowguid = this.$route.query.rowguid
        this.$api.selvendorlist(query).then(function (data) {
          _this.vendorObj = data.rows[0];
          _this.$api.applyfilelist({
            guaranteeid: rowguid,
            vendorid: data.rows[0].dwcode,
            isMobile: true,
            guaranteetype: _this.validateForm.guaranteetype
          }).then(function (res) {
            _this.filelist = res;
          })
        })
      },
      goPrve() {
        this.toPath('/order')
      },
      setTIme: function (e) {
        if (this.validateForm.kbtime && this.validateForm.indatenum) {
          let date = new Date(this.validateForm.kbtime).getTime();
          this.validateForm.enddate = this.timestampToTime(date + this.validateForm.indatenum * 86400000);
          this.validitytime = this.timestampToTime(date + this.validateForm.indatenum * 86400000);
        }
      },
      timestampToTime: function (timestamp) {
        let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        let Y = date.getFullYear() + '-';
        let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) +
          '-';
        let D = date.getDate();
        if (D <= 9) {
          D = '0' + D
        }
        return Y + M + D;
      },
      changeEar() {
        let that = this
        if (this.validateForm.earnest) {
          let query = {
            vendorcode: this.vendorObj.dwcode,
            bankcode: this.vendorObj.banklist[0].bankid,
            earnest: this.validateForm.earnest,
            guaranteetype: this.validateForm.guaranteetype
          }
          that.$api.computeprice(query).then(function (res) {
            console.log(res)
            that.validateForm.amount = res.price
            //that.$refs.price.innerText = res.price;
          })
        }
      },
      creatOrder: function () {
        this.$refs.form.validate().then((result) => {
          if (result) {
            var _this = this;
            let form = {
              bankid: this.vendorObj.banklist[0].bankid,
              bankname: this.vendorObj.banklist[0].bankname,
              vendorid: this.vendorObj.dwcode,
              vendorname: this.vendorObj.dwname,
              shbj: '1',
            }
            this.validateForm.kbtime = this.timestampToTime(this.validateForm.kbtime).split('T')[0];
            if (_this.rowguids) {
              form.rowguid = _this.rowguids
            }
            const loading = this.$loading({
              text: '创建订单中,请稍等...'
            });
            var form3 = $.extend({}, form, this.validateForm)
            console.log(form3)
            this.$api.createorder(form3).then(function (data) {
                if (!data) {
                  if (_this.$route.query.rowguid) {
                    _this.$router.push('/order')
                    loading.close()
                  } else {
                    _this.$router.push('/creatorder')
                    loading.close()
                  }
                }
              })
              .catch(function (error) {
                console.log(error)
              })
          }
        })

      },
      view(e) {
        ImagePreview([e])
      },
      viewAddress() {
        this.$dialog.alert({
          message: '河北省石家庄市中山东路126号凯嘉大厦10层'
        })
      },

      fileInput_change: function (e, item) {
        let _this = this;
        let formFile = new FormData();
        const loading = this.$loading();
        formFile.append("userFile", $(e.target)[0].files[0]);

        formFile.append("fileguid", item.fileguid || '');
        formFile.append("vendorid", _this.vendorObj.dwcode || '');
        formFile.append("filevendorid", item.filevendorid || '');
        formFile.append("guaranteeid", _this.$route.query.rowguid || '');
        formFile.append("filevendorname", item.filename || '');
        formFile.append("uptype", 'smj' || '');

        formFile.append("multifile", '0');
        $.ajax({
          type: "post",
          url: "/bhtong/ordermg/uploadfile.json",
          data: formFile,
          processData: false,
          contentType: false,
          success: function (data) {
            console.log(data)
            let res = data;
            if (res.code === 'v') {
              loading.close();
              _this.getselvendorlist();
            } else {
              loading.close();
              _this.$toast.fail(res.msg)
            }
          }
        })

      },
    },
    created() {
      let _this = this;
      let rowguid = this.$route.query.rowguid;
      if (rowguid) {
        this.$api.orderdetail({
          rowguid: rowguid
        }).then(function (res) {
          //   _this.$refs.price.innerText = res.orderinfo.amount ? res.orderinfo.amount : '';
          _this.validateForm = res.orderinfo;
          _this.getselvendorlist();

        })
      }
    },
    watch: {
      'validateForm.earnest': function (n, o) {
        let that = this;
        if (o != n) {
          if (n > 80) {
            that.common.showAlert('保证金金额不能超过80（不包括）万，请联系客服进行线下办理。', function () {
              that.validateForm.earnest = '';
            }, 'warning');
          } else {
            this.changeEar()
          }
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .van-tabs--line .van-tabs__wrap {
    position: fixed;
  }

  .container {
    padding: 16px;
  }

  .mu-text-field-input {
    border: none;
    background: #ffffff;
    height: 40px;
    border-radius: 5px;
    font-size: 12px;
  }

  .mu-form-item {
    margin-bottom: 4px;
    padding-bottom: 12px;

    .mu-buttons {
      margin: 0 auto;
      width: 100%;
      background-color: #f18241;
      margin-top: 20px;
    }

    .form_submit {
      color: #333333;
      background-color: #fff;
    }
  }

  .mu-primary-text-color,
  .selected,
  .now {
    color: #f18241;
  }

  .form_flex {
    display: flex;
    justify-content: flex-start;
  }

  .form_indate {
    line-height: 90px;
    margin-left: 30px;
    color: #666666
  }

  .form_unit {
    height: 40px;
    margin-top: 38px;
    margin-left: 10px;
    margin-right: 10px;
    width: 40px;
  }

  .form_btn {
    position: absolute;
    right: 0;
    top: 15px;
  }

  .form_container {
    margin-bottom: 100px;
    padding: 0;
  }

  .demo-paper {
    margin: 10px;
    padding: 15px;
  }

  .mu-buttons {
    margin: 0 auto;
    width: 100%;
    background-color: #ffffff;
    color: #333333;
    box-shadow: none;
    border: 1px solid #bbbbbb;
    border-radius: 5px;
  }

  .form_creat {
    background: #f18241;
    color: #fff;
    width: 40%
  }

  .form_submit {
    margin: 0;
    color: #fff;
    display: flex;
    justify-content: space-around;
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
  }

  .form_mar {
    margin-bottom: 60px;
  }

  .uploader__linput {
    position: absolute;
    left: 0;
    width: 49%;
    opacity: 0;
  }

  .uploader__rinput {
    position: absolute;
    right: 0;
    top: 0;
    width: 49%;
    opacity: 0;
  }
</style>